import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';

class AnjiaFlutBugly {
  static const MethodChannel _channel = const MethodChannel('anjia_flut_bugly');

  @deprecated
  static Future<String?> get platformVersion async {
    final String? version = await _channel.invokeMethod('getPlatformVersion');
    return version;
  }

  /// 上报自定义异常信息，[data] 为文本附件
  /// -Android 错误分析 => 跟踪数据 => extraMessage.txt
  /// -iOS 错误分析 => 跟踪数据 => crash_attach.log
  static Future<Null> uploadException({
    required Type type,
    required String message,
    StackTrace? stackTrace,
    Map? data,
  }) async {
    var map = {};
    map.putIfAbsent("type", () => type.toString());
    map.putIfAbsent("message", () => message);
    map.putIfAbsent("stackTrace", () => stackTrace?.toString() ?? "");
    if (data != null) map.putIfAbsent("data", () => data);
    await _channel.invokeMethod('postException', map);
  }

  /// [FlutterError.onError]
  static Future<Null> uploadException4FlutterErrorDetails(
      FlutterErrorDetails details) async {
    return uploadException(
      type: details.exception.runtimeType,
      message: details.exception.toString(),
      stackTrace: details.stack,
    );
  }

  /// [runZonedGuarded(body, onError)]
  static Future<Null> uploadException4OnError(
    Object error,
    StackTrace? stack,
  ) async {
    return uploadException(
      type: error.runtimeType,
      message: error.toString(),
      stackTrace: stack,
    );
  }
}
